/*
 * NPM: originally from QtSDK 1.1
 * /opt/QtSDK/Demos/4.7/declarative/webbrowser/content/FlickableWebView.qml
 *
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * Copyright (C) 2011 Niels Mayer <NielsMayer _AT_ gmail _DOT_ com>
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

import QtQuick 1.0
import QtWebKit 1.0

Flickable {                                             // NPM: http://doc.qt.nokia.com/4.7/qml-flickable.html
    property alias title:         webView.title
    property alias icon:          webView.icon
    property alias progress:      webView.progress
    property alias url:           webView.url
    property alias back:          webView.back
    property alias stop:          webView.stop
    property alias reload:        webView.reload
    property alias forward:       webView.forward
    property alias scale:         webView.contentsScale //NPM
    property alias sx:            flickable.contentX    //NPM
    property alias sy:            flickable.contentY    //NPM

    id: flickable
    width: parent.width
    contentWidth: Math.max(parent.width,webView.width)
    contentHeight: Math.max(parent.height,webView.height)
    anchors.top: parent.top   //NPM
    anchors.bottom: parent.top
    anchors.left: parent.left
    anchors.right: parent.right
    pressDelay:		0
    flickableDirection: Flickable.VerticalFlick
    interactive: false

// NPM: and this is irritating when exhibit bubbles popup
//    onWidthChanged : {
//        // Expand (but not above 1:1) if otherwise would be smaller that available width.
//        if (width > webView.width*webView.contentsScale && webView.contentsScale < 1.0)
//            webView.contentsScale = width / webView.width * webView.contentsScale;
//    }

    WebView { 						//NPM: http://doc.qt.nokia.com/4.7/qml-webview.html
        id: webView
        transformOrigin: Item.TopLeft
	pressGrabTime: 0                                //NPM:"The number of milliseconds the user must press before the WebView starts passing move events through to the Web engine (rather than letting other QML elements such as a Flickable take them)."
	settings.standardFontFamily: "Nokia Pure Text"

//NPM
//        function fixUrl(url)
//        {
//            if (url == "") return url
//            if (url[0] == "/") return "file://"+url
//            if (url.indexOf(":")<0) {
//                if (url.indexOf(".")<0 || url.indexOf(" ")>=0) {
//                    // Fall back to a search engine; hard-code Wikipedia
//                    return "http://en.wikipedia.org/w/index.php?search="+url
//                } else {
//                    return "http://"+url
//                }
//            }
//            return url
//        }
//
//        url: fixUrl(webBrowser.urlString)

        smooth: false // We don't want smooth scaling, since we only scale during (fast) transitions
        focus: true
        onAlert:		console.log("WebView onAlert: " + message); //NPM: http://doc.qt.nokia.com/latest/qml-webview.html#onAlert-signal
        onLoadFailed:		root.webViewReady(false);           //NPM: http://doc.qt.nokia.com/latest/qml-webview.html#onLoadFailed-signal
        onLoadFinished:		{                                   //NPM: http://doc.qt.nokia.com/latest/qml-webview.html#onLoadFinished-signal
				  // if 'checked="true"' is present in HTML definition for
				  // 'flickable-checkbox' then set the webView's flickability based on
				  // the specific app/example settings. Some examples work better in
				  // a flickable webview, whereas ones with embedded timeline or map
				  // don't because touch events that would normally go to the
				  // timeline or map are intercepted by flickable container. Let the app decide...
				  var isFlickable =    webView.evaluateJavaScript("SimileAjax.jQuery('input.flickable-checkbox')[0].checked")
				                    || webView.evaluateJavaScript("$('input.flickable-checkbox')[0].checked");
				  console.log("Setting flickable.interactive = " + isFlickable);
				  if (typeof(isFlickable) == "boolean")
                                      flickable.interactive = isFlickable;
				  else {
				      flickable.interactive = false;
				      console.log("Setting flickable.interactive based on HTML failed... defaulting to 'false'.");
				  }
                                  root.webViewReady(true);
				}
	javaScriptWindowObjects:QtObject {                             //NPM: http://doc.qt.nokia.com/latest/qml-webview.html#javaScriptWindowObjects-prop
				 WebView.windowObjectName: "qml"       //NPM: call from HTML as window.qml.showExampleChooser()
				 function showExampleChooser() { root.showExampleChooser(); }
				 function consoleLog(msg)      { console.log(msg); }  //WebView otherwise swallows console.log()
				 function consoleInfo(msg)     { console.info(msg); } //WebView otherwise swallows console.log()
				 function enableScroll(enable) { flickable.interactive = enable; }
				}

        function doZoom(zoom,centerX,centerY)
        {
            if (centerX) {
                var sc = zoom*contentsScale;
                scaleAnim.to = sc;
                flickVX.from = flickable.contentX
                flickVX.to = Math.max(0,Math.min(centerX-flickable.width/2,webView.width*sc-flickable.width))
                finalX.value = flickVX.to
                flickVY.from = flickable.contentY
                flickVY.to = Math.max(0,Math.min(centerY-flickable.height/2,webView.height*sc-flickable.height))
                finalY.value = flickVY.to
                quickZoom.start()
            }
        }

//NPM:  Key_Left and Key_Right are used by timeline so don't override.
//      Keys.onLeftPressed: webView.contentsScale -= 0.1
//      Keys.onRightPressed: webView.contentsScale += 0.1
	// NPM: do this instead. Since there's no onPlusPressed
	// or onMinusPressed, we do the following
	// http://doc.qt.nokia.com/latest/qml-keys.html
        Keys.onPressed: {
          if (event.key == Qt.Key_Plus) {
	      webView.contentsScale += 0.1;
              event.accepted = true;
          }
          if (event.key == Qt.Key_Minus) {
	      webView.contentsScale -= 0.1;
              event.accepted = true;
          }
          if (event.key == Qt.Key_0) {
	      webView.contentsScale = 1.0;
              event.accepted = true;
          }
        }

        preferredWidth: flickable.width
        preferredHeight: flickable.height
        contentsScale: 1
// NPM: and this is irritating when exhibit bubbles popup
//        onContentsSizeChanged: {
//            // zoom out
//            contentsScale = Math.min(1,flickable.width / contentsSize.width)
//        }
        onUrlChanged: {
            // got to topleft
            flickable.contentX = 0
            flickable.contentY = 0
//            if (url != null) { header.editUrl = url.toString(); } //NPM
        }

// NPM this ends up being annoying... use keyboard to zoom
//        onDoubleClick: {
//                        if (!heuristicZoom(clickX,clickY,2.5)) {
//                            var zf = flickable.width / contentsSize.width
//                            if (zf >= contentsScale)
//                                zf = 2.0*contentsScale // zoom in (else zooming out)
//                            doZoom(zf,clickX*zf,clickY*zf)
//                         }
//                       }

        SequentialAnimation {
            id: quickZoom

            PropertyAction {
                target: webView
                property: "renderingEnabled"
                value: false
            }
            ParallelAnimation {
                NumberAnimation {
                    id: scaleAnim
                    target: webView
                    property: "contentsScale"
                    // the to property is set before calling
                    easing.type: Easing.Linear
                    duration: 200
                }
                NumberAnimation {
                    id: flickVX
                    target: flickable
                    property: "contentX"
                    easing.type: Easing.Linear
                    duration: 200
                    from: 0 // set before calling
                    to: 0 // set before calling
                }
                NumberAnimation {
                    id: flickVY
                    target: flickable
                    property: "contentY"
                    easing.type: Easing.Linear
                    duration: 200
                    from: 0 // set before calling
                    to: 0 // set before calling
                }
            }
            // Have to set the contentXY, since the above 2
            // size changes may have started a correction if
            // contentsScale < 1.0.
            PropertyAction {
                id: finalX
                target: flickable
                property: "contentX"
                value: 0 // set before calling
            }
            PropertyAction {
                id: finalY
                target: flickable
                property: "contentY"
                value: 0 // set before calling
            }
            PropertyAction {
                target: webView
                property: "renderingEnabled"
                value: true
            }
        }
        onZoomTo: doZoom(zoom,centerX,centerY)
    }
}
